<template>
  <div>
    <div v-if="goodsId != null && goodsId !== '' && goodsId !== undefined && goodsId !== 0" v-loading="loading">
      <div v-if="goodsInfo" class="ExtendsGoodsInfo">
        <TableColumnGoodsImage :src="goodsInfo.commodityImage[0]" />
        <div class="goods-name">
          {{ goodsInfo.commodityName }}
        </div>
      </div>
      <div v-else>
        <div v-if="loading">加载商品信息中...</div>
        <div v-else>加载商品信息失败</div>
      </div>
    </div>
  </div>
</template>

<script>
import { getInfoById } from '@/api/commodity'
import TableColumnGoodsImage from '../TableColumnGoodsImage/index'

export default {
  name: 'ExtendsGoodsInfo',
  components: { TableColumnGoodsImage },
  props: {
    goodsId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      goodsInfo: null,
      loading: false,
      lastId: false
    }
  },
  watch: {
    goodsId: {
      handler(newVal, oldVal) {
        if (newVal !== this.lastId) {
          this.lastId = newVal
          this.getGoodsInfoById()
        }
      },
      immediate: true
    }
  },
  methods: {
    getGoodsInfoById() {
      const vm = this
      if (vm.goodsId == null || vm.goodsId === '' || vm.goodsId === undefined || vm.goodsId === 0) {
        vm.goodsInfo = null
        return
      }
      vm.loading = true
      getInfoById({ goodsId: this.goodsId }).then(res => {
        vm.loading = false
        vm.goodsInfo = res.data.data
        if (vm.goodsInfo.commodityName === undefined) {
          vm.goodsInfo = null
        }
      }).catch((res) => {
        vm.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.ExtendsGoodsInfo {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .goods-name {
    width: 100%;
    margin-left: 15px;
    text-align: left;
    font-size: 14px;
    color: #000000;
    word-break: break-all;
  }
}
</style>
